
import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

typedef Future<dynamic> EventHandler(dynamic event);

class AlipushFlutter {

  static const String flutter_log = "| ALIPUSH | Flutter | ";
  //单例
  factory AlipushFlutter() => _instance;
  //平台通道
  final MethodChannel _channel;
  //方法回调
  EventHandler? _onReceiveNotification;
  EventHandler? _onOpenNotification;
  EventHandler? _onNotificationClicked;

  AlipushFlutter.private(MethodChannel channel) : _channel = channel;

  static final AlipushFlutter _instance =
        new AlipushFlutter.private(const MethodChannel('com.jacky.util/alipush'));
  bool showLog = false;

  ///IOS 初始化设置
  void initIOS(String appKey, String appSecret) {
    print('iOS初始化了');
    if (Platform.isIOS) {
      _log(flutter_log + "setup:");
      _channel.invokeMethod('setup', {'appKey': appKey, 'appSecret': appSecret});
    }
  }

  void initOhos(String appKey, String appSecret) {
    print('ohos初始化了');
    if (Platform.operatingSystem == "ohos") {
      _log(flutter_log + "setup:");
      _channel.invokeMethod('setup', {'appKey': appKey, 'appSecret': appSecret});
    }
  }

  ///android初始化设置
  void initAndroid(String appKey, String appSecret,
      {String xiaomiId = '', String xiaomiKey = '', String oppoKey = '', String oppoSecret = '',
      String meizuAppId = '', String meizuAppKey = '', String gcmSendId = '', String gcmAppId = '',
        String gcmProjectId = '', String gcmApikey = ''}) {
    if (Platform.isAndroid) {
      _log(flutter_log + "setup:");
      _channel.invokeMethod('setup', {
        'appKey': appKey, 'appSecret': appSecret,
        'xiaomiId' : xiaomiId, 'xiaomiKey' : xiaomiKey,
        'oppoKey' : oppoKey, 'oppoSecret' : oppoSecret,
        'meizuAppId' : meizuAppId, 'meizuAppKey' : meizuAppKey,
        'gcmSendId' : gcmSendId, 'gcmAppId' : gcmAppId,
        'gcmProjectId' : gcmProjectId, 'gcmApikey' : gcmApikey
      });
    }
  }

  //是否开启日志输出,默认关闭
  void setLogEnable(bool enable) {
    showLog = enable;
    _channel.invokeMethod('setLogEnable', {'enable': enable});
  }

  /// 事件传递
  /// onReceiveNotification 当应用处于前台状态收到推送
  /// onOpenNotification   当通过点击通知栏打开应用
  void addEventHandler({
    EventHandler? onReceiveNotification,
    EventHandler? onOpenNotification,
    EventHandler? onNotificationClicked,
  }) {
    _log(flutter_log + "addEventHandler:");
    _onReceiveNotification = onReceiveNotification;
    _onOpenNotification = onOpenNotification;
    _onNotificationClicked = onNotificationClicked;
    _channel.setMethodCallHandler(_handleMethod);
  }

  Future _handleMethod(MethodCall call) async {
    _log(flutter_log + "_handleMethod:");
    switch (call.method) {
      case "onReceiveNotification":
        try {
          _onReceiveNotification?.call(call.arguments.cast<String, dynamic>());
        }catch(e) {
          debugPrint(e.toString());
        }
        break;
      case "onOpenNotification":
        try {
          _onOpenNotification?.call(call.arguments.cast<String, dynamic>());
        } catch (e) {
          debugPrint(e.toString());
        }
        break;
      case "onNotificationClicked":
        try {
          _onNotificationClicked?.call(call.arguments);
        } catch (e) {
          debugPrint(e.toString());
        }
        break;
      default:
        throw new UnsupportedError("Unrecognized Event ${call.method}");
    }
  }

  ///设置别名，ios int，Android string，看是否处理
  Future<bool> setAlias(String alias) async {
    _log(flutter_log + "setAlias:");
    dynamic result = await _channel.invokeMethod('setAlias', alias);
    return result != null;
  }

  ///删除别名，alias = null or alias.length = 0 时，删除设备全部别名。
  Future<bool> deleteAlias(String alias) async {
    _log(flutter_log + "deleteAlias:");
    dynamic result = await _channel.invokeMethod('deleteAlias',alias);
    return result != null;
  }

  /// 设置应用 Badge（小红点）,iOS自动管理一般不需要设置
  Future setBadge(int badge) async {
    _log(flutter_log + "setBadge:");
    await _channel.invokeMethod('setBadge', {"badge": badge});
  }

  /// 通知栏显示推送
  ///
  /// [title] 通知栏展示的标题
  ///
  /// [content] 通知栏展示的内容
  ///
  /// [params] 通知点击时的参数
  Future showNotification(String title, String content, {String? params, String? icon}) async {
    _log(flutter_log + "showNotification:");
    await _channel.invokeMethod('showNotification', {"title": title, "content":content, 'params':params, 'icon': icon});
  }

  ///当应用处于前台时收到推送，是否显示推送弹窗，默认否
  void setPushOnActive(bool active) async {
    _log(flutter_log + "setPushOnActive:");
    await _channel.invokeMethod('setPushOnActive', {"active": active});
  }

  void _setNotificationSoundFilePath(String filePath, int form) {
    if(Platform.isAndroid) {
      _channel.invokeMethod(
          "setNotificationSoundFilePath", {"filePath": filePath, "form" : form});
    }
  }

  ///将 [assets] 目录下的声音文件设置为通知栏的声音
  void setNotificationSoundFilePathFormAsset(String assetPath) {
    _setNotificationSoundFilePath(assetPath, 1);
  }

  ///将 [raw] 目录下的声音文件设置为通知栏的声音
  ///
  ///比如资源文件id为 R.raw.alicloud_notification_sound，则 [rawPath]为 alicloud_notification_sound
  ///
  /// 默认raw的资源名为 alicloud_notification_sound，可不调用该接口
  void setNotificationSoundFilePathFormRaw(String rawPath) {
    _setNotificationSoundFilePath(rawPath, 2);
  }

  ///设置通知栏的声音来源
  void setNotificationSoundFilePath(String filePath) {
    _setNotificationSoundFilePath(filePath, 3);
  }

  void _log(Object? string) {
    if(showLog) print(string);
  }
}